import axios from "axios";
import store from '../store';

// 配置axios请求的baseURL
axios.defaults.baseURL = import.meta.env.VITE_API_BASE;
axios.defaults.headers['Content-Type'];

// 配置响应拦截器
// axios.interceptors.response.use(
//   response => {
//     // 分析响应数据，处理响应拦截
//     return Promise.resolve(response);
//   },
//   error => {
//     // 处理错误
//     return Promise.reject(error);
//   }
// );

// 封装一般请求方法
const doRequest = (url = "", options = {}) => {
  return new Promise((resolve, reject) => {
    options.method = options.method || "GET";
    options.data = options.data || {};
    options.params = options.params || {};
    options.headers = options.headers || { 'TM-TOKEN': store.state.token };

    let req = {
      url: url,
      method: options.method,
      data: options.data,
      params: options.params,
      headers: options.headers
    }

    if (options.blob) {
      req = {...req, responseType: 'blob'}
    }
    
    axios.request(req)
    .then(response => {
      resolve(response);
    })
    .catch(error => {
      reject(error);
    });
  });
};

// 封装包含认证的一般请求方法
const doAuthRequest = (url = "", options = {}) => {
  return new Promise((resolve, reject) => {
    const token = localStorage.getItem("access_token") || '';
    options.params.token = token;
    doRequest(url, options)
    .then(response => {
      resolve(response);
    })
    .catch(error => {
      reject(error);
    });
  });
};

const request = {
  doRequest,
  doAuthRequest
};

export default request;
